package com.baosight.risk.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baosight.risk.api.code.ISqlCodeService;
import com.baosight.risk.api.fltd.FltdPressService;
import com.baosight.risk.api.fltd.FltdTaskService;
import com.baosight.risk.api.zbaa.IZbaaTargetService;
import com.baosight.risk.api.zbaa.IZbaaTargetValueService;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.pdf.dto.Office2PdfDto;
import com.baosight.risk.common.pdf.service.Office2PdfService;
import com.baosight.risk.common.quartz.TargetBsteelTask;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.HttpUtils;
import com.baosight.risk.common.utils.IDGenerator;
import com.baosight.risk.service.code.entity.SqlCode;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.zbaa.entity.ZbaaTarget;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetValue;
import com.baosight.risk.webservice.TargetOutWebService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import java.io.*;
import java.util.*;

/**
 * @author bazhandao
 * @description 测试Controller
 * @date 2019/7/18 16:50
 * @since JDK1.8
 */
@Api(value="测试内部方法接口",description = "测试内部方法接口",produces = MediaType.APPLICATION_JSON)
@Slf4j
@RestController
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    private Office2PdfService office2PdfService;

    @Autowired
    private ISqlCodeService sqlCodeService;

    @Autowired
    private TargetBsteelTask targetBsteelTask;

    @Autowired
    private FltdTaskService fltdTaskService;
    
    @Autowired
    private FltdPressService fltdPressService;

    @Autowired
    private TargetOutWebService targetOutWebService;

    @Autowired
    private IZbaaTargetValueService zbaaTargetValueService;

    @Autowired
    private IZbaaTargetService targetService;

    /**
     * 测试转换为pdf
     *
     * @return
     */
    @RequestMapping(value = "/2pdf")
    @ResponseBody
    public Office2PdfDto test() {
        String fileName = "/Users/Liqiurong/Desktop/1234.doc";
        File file = new File(fileName);
        Office2PdfDto office2PdfDto = office2PdfService.office2Pdf(file);
        return office2PdfDto;
    }

    /**
     * 测试异常
     */
    @RequestMapping(value = "/exception")
    @ResponseBody
    public AjaxResult testException() {
        log.info("数据插入异常：xxxxxxxx");
        SqlCode sqlCode = new SqlCode();
        sqlCode.setSqlcode("xxxxxxxx");
        sqlCodeService.delete(sqlCode);
        return AjaxResult.success();
    }

    /**
     * 测试异常
     */
    @RequestMapping(value = "/code")
    @ResponseBody
    public List<SqlCode> testcode() {
        log.info("测试删除：吊炸天");
        return sqlCodeService.queryAll();
    }

    @RequestMapping(value = "/clearCodeRedis")
    @ResponseBody
    public AjaxResult clearCodeRedis() {
        log.info("测试清空sql编号缓存");
        sqlCodeService.clearSqlCode();
        return AjaxResult.success();
    }


    /**
     * 测试转换为pdf
     *
     * @return
     */
    @RequestMapping(value = "/2pdf/byte")
    public void testByte(HttpServletResponse response) throws IOException {
        String fileName = "/Users/Liqiurong/Desktop/1234.doc";
        File file = new File(fileName);
        byte[] arr = office2PdfService.office2PdfByte(file);
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "filename=xxx.pdf");
        response.setContentLength(arr.length);
        response.getOutputStream().write(arr);
    }

    /**
     * 测试催办发送
     *
     * @return
     */
    @GetMapping(value = "/urgent")
    @ApiOperation("测试催办发送")
    public AjaxResult testUrgent() throws Exception {
        List<FltdTask> tasks = fltdTaskService.selectTaskList("3", new FltdTaskVO(), "");
        Map<String, Map<String, Object>> resultMap = fltdPressService.convertUrgentTasks(tasks);
        return AjaxResult.success();
    }

    /**
     * 测试东方钢铁接口
     *
     * @return
     */
    @GetMapping(value = "/bsteel")
    @ApiOperation("测试东方钢铁接口，导入历史数据")
    public AjaxResult testBsteel(String filePath) throws Exception {
        targetBsteelTask.getDataByHistory(filePath);
        return AjaxResult.success();
    }

    public static void main(String[] args) throws Exception {
        String URL = "http://ai.ibaosteel.com/bsi/baoxin/indexData";

        Calendar date = Calendar.getInstance();
        date.set(Calendar.YEAR, 2018);
        date.set(Calendar.MONTH, 0);
        date.set(Calendar.DAY_OF_MONTH, 1);

        Calendar calendar = Calendar.getInstance();

        int day = (int) ((calendar.getTime().getTime()-date.getTime().getTime()) / (1 * 24 *60 * 60 * 1000));

        System.out.println(day);

//        new TargetBsteelTask().getDataByHistory("C:/Users/VULCAN/Desktop/东方钢铁接口历史数据");

        //循环调用接口，按天获取数据
        for (int i = 0; i < day; i++) {
            calendar.add(Calendar.DATE, -1);
            String yesterday = DateUtils.formatYYYY_MM_DD(calendar.getTime());

            String resultData = null;
            try {
                String getUrl = URL + "?time="+ yesterday;
                resultData = HttpUtils.sendGet(getUrl);

                String fileName ="C:\\Users\\VULCAN\\Desktop\\东方钢铁接口历史数据\\" + yesterday + ".txt";

                File file = new File(fileName);

                if (file.exists()) {
                    file.delete();
                } else {
                    file.createNewFile();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
                    writer.write(resultData);
                    writer.flush();
                    writer.close();
                }

            } catch (Exception e) {
                System.out.println("获取东方钢铁接口数据异常！指标日期："+yesterday+"，接口返回："+resultData+"，异常信息："+e.getMessage());
            }
        }
    }

    /**
     * 测试wind接口
     *
     * @return
     */
    @GetMapping(value = "/outWind")
    @ApiOperation("测试Wind接口，导入历史数据")
    public AjaxResult testOutWind() throws Exception {

        // 结束时间
        Calendar end = Calendar.getInstance();
        // 起始时间
        Calendar base = Calendar.getInstance();
        base.set(2019, 0, 1);

        for (;;) {
            // 获取昨日日期
            Date date = base.getTime();
            String nowDate = DateUtils.format(date, "yyyy-MM-dd");
            String yesterday = DateUtils.caculateTime(nowDate, "日", "1");

            File file = new File("C:\\Users\\VULCAN\\Desktop\\Wind数据\\"+yesterday+".txt");
            if (!file.exists()) {
                base.add(Calendar.DAY_OF_MONTH, 1);
                continue;
            }
//            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            BufferedReader br = new BufferedReader(new FileReader(file));
            try {
                //传入参数，调用指标值获取接口数据
                // String jsonString = "[{\"beginTime\":\"2019-09-11\",\"endTime\":\"2019-09-11\",\"targetNo\":\"\"}]";
//                String jsonString = "[{\"beginTime\":\"" + yesterday + "\",\"endTime\":\"" + yesterday + "\",\"targetNo\":\"\"}]";
//                String dataResult = targetOutWebService.sendRequestResult(jsonString);
//                System.out.println("接口返回："+dataResult);
//                bw.write(dataResult);

                String dataResult = br.readLine();

                //处理获取的接口数据
                List<ZbaaTargetValue> list = dataHandle(dataResult);

                if (list.size() > 0) {
                    // 批量插入处理后的数据
                    zbaaTargetValueService.insertValueList(list);
                    System.out.println(yesterday+"新增数据：" + list.size());
                }
            } catch (Exception e) {
                String str = String.format("%s 获取 %s 外部指标数据出错！", nowDate, yesterday);
                log.info(str);
                log.info(e.toString());
                throw e;
            } finally {
//                bw.close();
                br.close();
            }

            base.add(Calendar.DAY_OF_MONTH, 1);
            if (base.after(end)) {
                break;
            }
        }



        log.info("定时任务——获取外部指标方法完成");

        return AjaxResult.success();
    }

    /**
     * @param dataResult
     * @return
     * @description 处理接口中获得的指标数据
     * @author CuiShiHao
     */
    private List<ZbaaTargetValue> dataHandle(String dataResult) {

        //处理后数据（仅插入可以对应到targetNo的数据）
        List<ZbaaTargetValue> resultList = new ArrayList<>();
        //查询所有指标数据
        List<ZbaaTarget> targetList = targetService.getTargetList(new ZbaaTarget());

        //处理指标数据，更新targetNo
        JSONObject jsonObject = JSONObject.parseObject(dataResult);
        JSONArray data = jsonObject.getJSONArray("data");
        List<ZbaaTargetValue> list = JSONObject.parseArray(data.toJSONString(), ZbaaTargetValue.class);
        for (ZbaaTargetValue zbaaTargetValue : list) {
            zbaaTargetValue.setCreateBy("admin");
            zbaaTargetValue.setId(IDGenerator.getIdStr());
            zbaaTargetValue.setPeriodNo(zbaaTargetValue.getTargetPeriod());

            for (ZbaaTarget zbaaTarget : targetList) {
                if (zbaaTarget.getTargetNo().equals(zbaaTargetValue.getTargetNo())) {
                    // 根据周期处理TargetPeriod
                    String targetPeriodName = zbaaTarget.getTargetPeriodName();
                    String periodNo = handleTargetPeriod(zbaaTargetValue.getTargetPeriod(), targetPeriodName);
                    zbaaTargetValue.setPeriodNo(periodNo);
                    zbaaTargetValue.setAcctYear(periodNo.substring(0, 4));
                    if (periodNo.length() > 4) {
                        zbaaTargetValue.setAcctPeriod(periodNo.substring(4, 6));
                    }
                    // 填充代码逻辑中非必要参数
                    zbaaTargetValue.setTargetPeriod(zbaaTarget.getTargetPeriod());
                    zbaaTargetValue.setTargetPeriodName(zbaaTarget.getTargetPeriodName());
                    zbaaTargetValue.setSysSource(zbaaTarget.getSysSource());
                    zbaaTargetValue.setSysSourceName(zbaaTarget.getSysSourceName());
                    zbaaTargetValue.setRiskSource("W");
                    zbaaTargetValue.setRiskSourceName("外部指标");
                    resultList.add(zbaaTargetValue);
                    break;
                }
            }
        }
        return resultList;
    }


    /**
     * @param periodNo         传入的periodNo
     * @param targetPeriodName 周期名称
     * @return
     * @description 描述
     * @author CuiShiHao
     */
    private String handleTargetPeriod(String periodNo, String targetPeriodName) {

        String result = "";
        switch (targetPeriodName) {
            case "年":
                result = periodNo.substring(0, 4);
                break;
            case "月":
                result = periodNo.substring(0, 6);
                break;
            case "日":
                result = periodNo;
                break;
            case "季":
                result = dealQuarter(periodNo);
                break;
        }
        return result;
    }

    /**
     * @param periodNo 周期
     * @return
     * @description 描述
     * @author CuiShiHao
     */
    public String dealQuarter(String periodNo) {
        String year = periodNo.substring(0, 4);
        String month = periodNo.substring(4, 6);
        String result = "";
        switch (month) {
            case "1":
            case "2":
            case "3":
                result = "Q1";
                break;
            case "4":
            case "5":
            case "6":
                result = "Q2";
                break;
            case "7":
            case "8":
            case "9":
                result = "Q3";
                break;
            case "10":
            case "11":
            case "12":
                result = "Q4";
                break;
        }
        return year + result;
    }

    /**
     * 测试构建个人指标分析的树
     *
     * @return
     */
    @GetMapping(value = "/targetTree")
    @ApiOperation("测试构建个人指标分析的树")
    public AjaxResult targetTree(){
        return AjaxResult.success("查询成功", targetService.getTargetTree("person"));
    }

    /**
     * 测试指标值的修改
     *
     */
    @GetMapping(value = "/testTagert")
    @ApiOperation("测试指标值的修改")
    public AjaxResult testTagert(){
        zbaaTargetValueService.test();
        return AjaxResult.success();
    }


}
